import TencentCloudChat, { Message } from '@tencentcloud/chat'
import { useTencentChat } from '@/stores/tencentChat.ts'

export const useTencentMessageStore = defineStore('TencentMessage', () => {
  const tencentChat = useTencentChat()
  const tempMsgList = ref<Message[]>([])
  const nextReqMessageID = ref<string | undefined>()
  const isCompleted = ref<boolean>(false)
  const messageListHopping = ref<Message[]>([])
  const nextMessageSeq = ref<string | undefined>()
  const isCompletedHopping = ref<boolean>(false)
  const isLoading = ref<boolean>(false)
  const messageListMap = reactive<Record<string, Message[]>>({})
  const nextReqMessageIDMap = reactive<Record<string, string>>({})
  const isCompletedMap = reactive<Record<string, boolean>>({})

  /**
   *
   * @param options
   * {
   *     conversationID,
   *     nextReqMessageID
   *  }
   */
  const getMessageList = (options: any) => {
    const convID = options.conversationID
    if (!convID) {
      return
    }

    if (messageListMap[convID] === undefined) {
      messageListMap[convID] = []
    }

    if (isCompletedMap[convID] === undefined) {
      isCompletedMap[options.conversation] = false
    }
    console.log('进入消息列表...', messageListMap[convID], messageListMap[convID].length, isCompletedMap[convID])

    if (isCompletedMap[convID]) return
    isLoading.value = true
    options.nextReqMessageID = nextReqMessageIDMap[convID]
    tencentChat.chat?.getMessageList(options).then(res => {
      nextReqMessageIDMap[convID] = res.data.nextReqMessageID
      isCompletedMap[convID] = res.data.isCompleted
      isLoading.value = false
      let temp = res.data.messageList.filter((item: Message) => item.type !== TencentCloudChat.TYPES.MSG_CUSTOM)
      // 过滤自定义消息
      if (!tempMsgList.value.length) {
        if (!isCompletedMap[convID] && temp.length < 15 && messageListMap[convID].length === 0) {
          console.log('temp length', temp.length)
          tempMsgList.value = [
            ...temp,
            ...tempMsgList.value
          ]

          return
        }
      } else {
        console.log('next req message ID', nextReqMessageIDMap[convID])
        tempMsgList.value = []
      }

      messageListMap[convID] = [...temp, ...tempMsgList.value, ...messageListMap[convID]]
      console.log('获取成功', temp, res.data.isCompleted, messageListMap[convID])
    }).catch(error => {
      console.log(`获取消息列表：${error}`)
    })
  }

  watch(
    tempMsgList,
    (newVal) => {
      console.log('temp msg list', newVal)
      if (!newVal.length || newVal.length > 15 || isLoading.value) return
      const convId = newVal[0].conversationID
      if (convId && !isCompletedMap[convId]) {
        getMessageList({ conversationID: convId })
      }
    },
    {
      immediate: true,
      deep: true
    }
  )

  const getMessageListHopping = (options: any) => {
    // options = {
    //   conversationID: 'GROUPtest',
    //   sequence: nextMessageSeq,
    //   count: 15,
    //   direction: 0
    // }
    // 根据 sequence 拉群漫游消息，direction 0 向上拉，拉更旧的消息，direction 1 向下拉，拉更新的消息
    tencentChat.chat?.getMessageListHopping(options).then(function(imResponse) {
      const { messageList, isCompleted, nextMessageSeq } = imResponse.data;
      // messageList - 消息列表
      // isCompleted - 拉取完成标识， true 已拉完，false 未拉完，可以通过 nextMessageSeq 的返回值进行续拉
      // nextMessageSeq - 续拉起始 sequence，当 isCompleted 返回 true 时，nextMessageSeq 返回空字符串
      messageListHopping.value = messageList
      isCompletedHopping.value = isCompleted
      nextMessageSeq.value = nextMessageSeq
    });
  }

  /**
   * 设置消息提示方式
   * @param options
   */
  const setMessageRemindType = async (options: any) => {
    await tencentChat.chat?.setMessageRemindType(options).then(res => {
      // 设置成功后 SDK 会触发 TencentCloudChat.EVENT.CONVERSATION_LIST_UPDATED 事件
      // TODO
      console.log('set message remind type', res)
    })
  }

  const sendMessage = (message: Message) => {
    tencentChat.chat?.sendMessage(message).then(function(imResponse) {
      // 发送成功
      console.log('发送成功', imResponse);
      if (imResponse.data.message.type !== TencentCloudChat.TYPES.MSG_CUSTOM) {
        messageListMap[imResponse.data.message.conversationID].push(imResponse.data.message)
      }
      // window.$message.success('发送成功')
    }).catch(function(imError) {
      // 发送失败
      console.warn('sendMessage error:', imError);
      window.$message.error(`发送失败${imError.message}`)
    });
  }

  const modifyMessage = (message: Message) => {
    // 将 txtMessage 的文本内容改为 "Hello Tencent"
    message.payload.text = "Hello Tencent";
    tencentChat.chat?.modifyMessage(message).then(function(imResponse) {
      const { message } = imResponse.data;
      console.log('modify message', message)
      // 修改消息成功，message 是最新的消息
    }).catch(function(imError) {
      // 修改消息失败
      const { code, data } = imError;
      console.log('modify message error', data)
      if (code === 2480) {
        // 修改消息发生冲突，data.message 是最新的消息
      } else if (code === 2481) {
        // 不支持修改直播群消息
      } else if (code === 20026) {
        // 消息不存在
      }
    })
  }

  const deleteMessage = (messageList: Message[]) => {
    tencentChat.chat?.deleteMessage(messageList).then(function(imResponse) {
      // 删除消息成功
      console.log('delete message', imResponse)
    }).catch(function(imError) {
      // 删除消息失败
      console.warn('deleteMessage error:', imError);
    });
  }

  const clearHistoryMessage = (conversationID: string) => {
    // 清空单聊的本地及云端的消息
    tencentChat.chat?.clearHistoryMessage(conversationID).then(function(imResponse) {
      // 清空消息成功
      console.log('clear history message', imResponse)
      window.$message.success('已清空聊天记录')
    }).catch(function(imError) {
      window.$message.error('错误', imError.message); // 清空消息失败的相关信息
    });
  }

  const revokeMessage = async (message: Message) => {
    // 主动撤回消息
    await tencentChat.chat?.revokeMessage(message).then(function(imResponse: any) {
      console.log('revoke message', imResponse)
      window.$message.success('消息已撤回')
      // 消息撤回成功
    }).catch(function(imError: any) {
      window.$message.error('消息撤回失败: ' + imError.message)
      // 消息撤回失败
      console.error('revokeMessage error:', imError);
    });
  }

  const sendMessageReadReceipt = (messageList: Message[]) => {
    tencentChat.chat?.sendMessageReadReceipt(messageList).then(function() {
      // 发送群消息已读回执成功
    }).catch(function(imError) {
      // 发送群消息已读回执失败
      console.error('send message read receipt error', imError)
    })
  }

  const getMessageReadReceiptList = (messageList: Message[]) => {
    tencentChat.chat?.getMessageReadReceiptList(messageList).then(function(imResponse) {
      messageList = imResponse.data.messageList; // 消息列表
      // 成功后，Message.readReceiptInfo 包含消息的已读回执信息
      // Message.readReceiptInfo.isPeerRead - 对端是否已发送已读回执
    }).catch(function(imError) {
      // 拉取已读回执列表失败
      console.error('get message read receipt list error', imError)
    })
  }

  const findMessage = (messageID: string) => {
    let message = tencentChat.chat?.findMessage(messageID);
    if (message) {
      // 读取 message 相关属性，如已读回执信息 readReceiptInfo
    }
  }

  const searchCloudMessage = (options: any) => {
    options = {
      keywordList: ['你好', '在哪里'],
      timePosition: Number((new Date().getTime()/1000).toFixed(0)),
      timePeriod: 24 * 60 * 60,
    }
    // 全量搜索，指定关键字和时间（过去一天）搜索
// - 搜索过去一天，消息里出现了 ‘你好’ 或 ‘在哪里’的消息
    tencentChat.chat?.searchCloudMessages(options).then(function(imResponse) {
      // 搜索消息成功
      const { totalCount, cursor, searchResultList } = imResponse.data;
      console.log(totalCount); // 满足搜索条件的消息所在的所有会话总数量
      console.log(cursor); // 下一次云端搜索的起始位置, 如果没有表示搜索结果拉取完成
      console.log(searchResultList); // 满足搜索条件的消息根据会话 ID 分组，分页返回分组结果
      for (let i = 0; i < searchResultList.length; i++) {
        const searchResultItem = searchResultList[i];
        const { conversationID, messageCount, messageList } = searchResultItem;
        console.log(conversationID); // 会话 ID
        console.log(messageCount); // 当前会话一共搜索到了多少条符合要求的消息
        // 本次搜索【全部会话】，那么 messageList 中装载的消息条数会有如下两种可能：
        // - 如果某个会话中匹配到的消息条数 > 1，则 messageList 为空，您可以在 UI 上显示“ messageCount 条相关记录”。
        // - 如果某个会话中匹配到的消息条数 = 1，则 messageList 为匹配到的那条消息，您可以在 UI 上显示之，并高亮匹配关键词。
        console.log(messageList);
      }
    }).catch(function(imError) {
      console.error(imError); // 搜索消息失败
    });
  }

  return {
    getMessageList,
    nextReqMessageID,
    isCompleted,
    setMessageRemindType,
    sendMessage,
    modifyMessage,
    getMessageListHopping,
    messageListHopping,
    isCompletedHopping,
    nextMessageSeq,
    deleteMessage,
    clearHistoryMessage,
    revokeMessage,
    sendMessageReadReceipt,
    getMessageReadReceiptList,
    findMessage,
    searchCloudMessage,
    isLoading,
    messageListMap,
    nextReqMessageIDMap,
    isCompletedMap,
  }
},
  {
    share: {
      enable: true,
      initialize: true
    }
  }
)
